import { useDebounceFn } from 'ahooks';
import { Select } from 'antd';
import React, { useState, useEffect } from 'react';
import { SelectOption } from '../../../types';

const { Option } = Select;

interface RemoteSelectProps {
  placeholder?: string;
  remote?: (value?: string | number | undefined) => Promise<any>;
  value?: string | number | undefined;
  onChange?: (value?: string | number | undefined) => void;
  onSelected?: (item?: SelectOption | undefined) => void;
  [key: string]: any;
}

const RemoteSelect: React.FC<RemoteSelectProps> = function ({
  remote,
  placeholder,
  value,
  onChange,
  onSelected,
  ...props
}) {
  const [state, setState] = useState<string | number | undefined>();
  const [options, setOptions] = useState<SelectOption[]>([]);

  useEffect(() => {
    if (value !== state) setState(value);
  }, [value]);

  const changeValue = (v?: string | number | undefined) => {
    if (onChange) onChange(v);
    else setState(v);
    onSelected && onSelected(options.find((item) => item.value === v));
  };

  const { run: debounceFetcher } = useDebounceFn(
    async (value: string | number | undefined) => {
      if (remote) {
        const list = await remote(value);
        setOptions(list || []);
      } else {
        setOptions([]);
      }
    },
    { wait: 300 },
  );
  return (
    <div>
      <Select
        {...props}
        placeholder={placeholder}
        showSearch
        filterOption={false}
        value={state}
        onChange={changeValue}
        onSearch={debounceFetcher}
      >
        {options.map((opt) => (
          <Option key={opt.value as string} value={opt.value as string}>
            {opt.label}
          </Option>
        ))}
      </Select>
    </div>
  );
};

export default RemoteSelect;
